package com.fansl.koala.quickdev.module.koala.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fansl.koala.quickdev.common.enums.ResultEnum;
import com.fansl.koala.quickdev.common.exception.BizException;
import com.fansl.koala.quickdev.module.koala.entity.UserEverydayStatisticDetail;
import com.fansl.koala.quickdev.module.koala.entity.UserVip;
import com.fansl.koala.quickdev.module.koala.service.IShareStatisticService;
import com.fansl.koala.quickdev.module.koala.vo.EverydayTaskInfoVo;
import com.fansl.koala.quickdev.module.koala.vo.UserTaskInfoVo;
import com.fansl.koala.quickdev.module.koala.vo.UserVipShareInfoVo;
import com.fansl.koala.quickdev.module.koala.vo.UserVipShareTimeLineVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fansl
 * @Description: vip任务打卡
 * @date 2020/5/6 11:16
 */
@Service
public class ShareStatisticServiceImpl implements IShareStatisticService {
    @Resource
    private UserServiceImpl userService;
    @Resource
    private UserVipServiceImpl userVipService;
    @Resource
    private UserEverydayStatisticDetailServiceImpl userEverydayStatisticDetailService;

    /**
     * 获取用户的vip打卡情况
     *
     * @param tel 手机号
     * @return vip打卡详情
     */
    @Override
    public UserVipShareInfoVo getStatisticVipShareInfo(String tel) {
        Long userId = this.userService.getStudentIdByTel(tel);
        if (ObjectUtil.isNull(userId) || userId <= 0) {
            throw new BizException(ResultEnum.ACCOUNT_NOT_FOUND);
        }
        UserVip userVip = this.userVipService.getByUserId(userId);
        String userVipTime = "";
        List<UserVipShareTimeLineVo> shareTimeLines = new ArrayList<>();
        int canShareDays = 0;
        int shareDays = 0;
        if (ObjectUtil.isNotNull(userVip) && ObjectUtil.isNotNull(userVip.getLiveCreateTime())) {
            LocalDateTime vipTime = userVip.getLiveCreateTime();
            userVipTime = DateUtil.format(Date.from(vipTime.atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd");
            int daysNum = (int) (LocalDate.now().toEpochDay() - vipTime.toLocalDate().toEpochDay());
            Map<String, UserVipShareTimeLineVo> userVipShareTimeLineMap = new HashMap<>(daysNum);
            canShareDays = daysNum + 1;
            for (int i = 0; i <= daysNum; i++) {
                LocalDateTime betweenTime = vipTime.plusDays(i);
                String shareTime = DateUtil.format(Date.from(betweenTime.atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd");
                UserVipShareTimeLineVo shareTimeLine = new UserVipShareTimeLineVo();
                shareTimeLine.setShareDate(betweenTime.toLocalDate());
                shareTimeLine.setShared(Boolean.FALSE);
                userVipShareTimeLineMap.put(shareTime, shareTimeLine);
            }
            List<UserEverydayStatisticDetail> shareInfo = this.userEverydayStatisticDetailService.getUserVipShareInfo(userId, LocalDateTime.of(vipTime.toLocalDate(), LocalTime.MIN));
            shareInfo.forEach(userEverydayStatisticDetail -> {
                String statisticDate = DateUtil.format(Date.from(userEverydayStatisticDetail.getStatisticDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd");
                if (userVipShareTimeLineMap.get(statisticDate) != null) {
                    userVipShareTimeLineMap.get(statisticDate).setShared(Boolean.TRUE);
                }
            });
            shareDays = shareInfo.size();
            shareTimeLines = userVipShareTimeLineMap.values().stream()
                    .sorted(Comparator.comparing(UserVipShareTimeLineVo::getShareDate).reversed())
                    .collect(Collectors.toList());
        }
        UserVipShareInfoVo userVipShareInfo = new UserVipShareInfoVo();
        userVipShareInfo.setUserId(userId);
        userVipShareInfo.setTel(tel);
        userVipShareInfo.setUserVipTime(userVipTime);
        userVipShareInfo.setShareTimeLineList(shareTimeLines);
        userVipShareInfo.setCanShareDays(canShareDays);
        userVipShareInfo.setShareDays(shareDays);
        return userVipShareInfo;
    }

    /**
     * 获取用户某天的任务完成情况
     *
     * @param userId   用户ID
     * @param taskDate 任务日期
     * @return 任务完成情况
     */
    @Override
    public UserTaskInfoVo getUserTaskInfo(Long userId, String taskDate) {
        DateTime dateTime = DateUtil.parse(taskDate, DatePattern.NORM_DATE_PATTERN);
        List<UserEverydayStatisticDetail> details =
                this.userEverydayStatisticDetailService.getTaskInfoInDate(userId,dateTime);
        List<EverydayTaskInfoVo> everydayTaskInfoVos = details.stream().map(detail->{
            EverydayTaskInfoVo everydayTaskInfoVo = new EverydayTaskInfoVo();
            everydayTaskInfoVo.setTaskType(detail.getTaskType());
            everydayTaskInfoVo.setTaskDetailType(detail.getTaskCategoryType());
            everydayTaskInfoVo.setTaskCount(detail.getTaskCount());
            String lastCompleteDate = "";
            if(detail.getUpdateTime()!=null){
                lastCompleteDate = detail.getUpdateTime()
                        .format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
            }else {
                lastCompleteDate = detail.getCreateTime()
                        .format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
            }
            everydayTaskInfoVo.setCompleteDate(lastCompleteDate);

            return everydayTaskInfoVo;
        }).collect(Collectors.toList());

        UserTaskInfoVo userTaskInfoVo = new UserTaskInfoVo();
        userTaskInfoVo.setUserId(userId)
                .setTaskDate(taskDate)
                .setEverydayTaskInfoVos(everydayTaskInfoVos);
        return userTaskInfoVo;
    }
}
